<template>
  <view class="confirm-order-page">
    <!-- 主内容区域 -->
    <scroll-view scroll-y class="content-scroll">
      <!-- 订单详情卡片 -->
      <view class="order-detail-card">
        <!-- 订单标题和标签 -->
        <view class="order-header">
          <view class="title-wrapper">
            <text class="order-title">{{ orderDetail.title || '加载中...' }}</text>
            <view class="buddy-type-badge">{{ orderDetail.buddyTypeName || '搭子' }}</view>
          </view>
          <view class="order-tags">
            <view
              :class="['status-tag', `status-${orderDetail.status}`]"
              :style="getStatusStyle(orderDetail.status)"
            >
              {{ getStatusText(orderDetail.status) }}
            </view>
          </view>
        </view>

        <!-- 发布时间 -->
        <text class="publish-time">发布于{{ orderDetail.publishTime }}</text>

        <!-- 活动时间 -->
        <view class="event-time">
          <image src="/static/time.png" class="event-icon" mode="aspectFit"></image>
          <text>{{ orderDetail.eventTime }}</text>
        </view>

        <!-- 活动地点 -->
        <view class="event-location">
          <image src="/static/location-small.png" class="event-icon" mode="aspectFit"></image>
          <text>{{ orderDetail.location }}</text>
        </view>

        <!-- 活动详情标签 -->
        <view class="detail-tags">
          <view class="detail-tag">{{ orderDetail.genderRestriction }}</view>
          <view class="detail-tag">{{ orderDetail.participantCount }}人</view>
          <view class="detail-tag">距离{{ orderDetail.distance }}</view>
        </view>

        <!-- 价格 -->
        <view class="price-section">
          <text class="price">¥{{ orderDetail.price || 0 }}</text>
        </view>

        <!-- 背景装饰 -->
        <view class="card-bg">
          <image src="/static/game.png" class="bg-image" mode="aspectFit"></image>
        </view>
      </view>

      <!-- 接单人列表 -->
      <view class="accepter-list-card">
        <view class="list-header">
          <text class="list-title">接单人列表</text>
          <text class="list-count">{{ confirmedCount }}/{{ orderDetail.participantCount }}人</text>
        </view>

        <view class="accepter-list">
          <view 
            v-for="(user, index) in accepterList" 
            :key="user.id || index" 
            class="accepter-item"
          >
            <image 
              :src="user.avatar || '/static/avatars/default_avatar.png'" 
              class="accepter-avatar"
              mode="aspectFill"
            ></image>
            <view class="accepter-info">
              <text class="accepter-name">{{ user.nickname || user.name || '匿名用户' }}</text>
              <!-- 进行中状态：显示待确认 -->
              <text v-if="user.status === 1" class="status-text pending">待对方确认</text>
              <!-- 待发布人确认状态：显示已确认 -->
              <text v-else-if="user.status === 4" class="status-text confirmed">对方已确认</text>
            </view>
            <view class="accepter-actions">
              <!-- 已拒绝状态 -->
              <view v-if="user.status === 2" class="status-badge rejected">
                已拒绝
              </view>
              <!-- 进行中状态（待确认）：显示拒绝按钮 -->
              <view v-else-if="user.status === 1" class="action-buttons">
                <button 
                  class="action-btn reject-btn" 
                  @click="handleReject(user)"
                  :disabled="actionLoading"
                >
                  拒绝
                </button>
              </view>
              <!-- 待发布人确认状态（已确认）：显示拒绝和确认按钮 -->
              <view v-else-if="user.status === 4" class="action-buttons">
                <button 
                  class="action-btn reject-btn" 
                  @click="handleReject(user)"
                  :disabled="actionLoading"
                >
                  拒绝
                </button>
                <button 
                  class="action-btn confirm-btn" 
                  @click="handleConfirm(user)"
                  :disabled="actionLoading"
                >
                  确认
                </button>
              </view>
              <!-- 其他状态（待确认）：显示拒绝和确认按钮 -->
              <view v-else class="action-buttons">
                <button 
                  class="action-btn reject-btn" 
                  @click="handleReject(user)"
                  :disabled="actionLoading"
                >
                  拒绝
                </button>
                <button 
                  class="action-btn confirm-btn" 
                  @click="handleConfirm(user)"
                  :disabled="actionLoading"
                >
                  确认
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import BuddyApi from '@/sheep/api/member/buddy';

const orderId = ref(null);
const orderDetail = ref({});
const accepterList = ref([]);
const loading = ref(false);
const actionLoading = ref(false);

const formatDateTime = (time) => {
  if (!time) return '--';
  try {
    const date = new Date(time);
    if (Number.isNaN(date.getTime())) {
      return typeof time === 'string' ? time : '--';
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`;
  } catch (err) {
    console.error('formatDateTime error:', err);
    return typeof time === 'string' ? time : '--';
  }
};

const formatEventTime = (time) => {
  if (!time) return '待定';
  try {
    const date = new Date(time);
    if (Number.isNaN(date.getTime())) {
      return typeof time === 'string' ? time : '待定';
    }
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${month}月${day}日 ${hours}:${minutes}`;
  } catch (err) {
    console.error('formatEventTime error:', err);
    return typeof time === 'string' ? time : '待定';
  }
};

const formatGenderLimit = (genderLimit) => {
  if (genderLimit === 1 || genderLimit === '1') return '仅限男生';
  if (genderLimit === 2 || genderLimit === '2') return '仅限女生';
  return '男女不限';
};

const formatDistance = (distance) => {
  if (distance === null || distance === undefined || distance === '') return '--';
  const value = Number(distance);
  if (Number.isNaN(value)) {
    return typeof distance === 'string' ? distance : '--';
  }
  if (value < 1000) {
    return `${Math.round(value)}m`;
  }
  return `${(value / 1000).toFixed(1)}km`;
};

// 我发布的订单状态映射：0-接单中，1-进行中，2-已完成，3-已取消
const normalizePublishedStatus = (status) => {
  if (status === null || status === undefined) return 'taking';
  const numeric = Number(status);
  if (!Number.isNaN(numeric)) {
    if (numeric === 0) return 'taking';      // 接单中
    if (numeric === 1) return 'in_progress'; // 进行中
    if (numeric === 2) return 'completed';   // 已完成
    if (numeric === 3) return 'cancelled';   // 已取消
  }
  const value = String(status).toLowerCase();
  if (['taking', 'pending', 'waiting', 'accepting', 'open'].includes(value)) return 'taking';
  if (['in_progress', 'processing', 'ongoing', 'running', 'doing'].includes(value)) return 'in_progress';
  if (['completed', 'finished', 'done', 'success', 'succeed'].includes(value)) return 'completed';
  if (['cancelled', 'canceled', 'closed', 'void'].includes(value)) return 'cancelled';
  return 'taking';
};

const getStatusText = (status) => {
  const statusMap = {
    'taking': '接单中',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status] || status || '未知状态';
};

const getStatusStyle = (status) => {
  const styleMap = {
    'in_progress': 'linear-gradient(90deg, #EE1C1C 0%, #FFB96F 67%, rgba(255, 185, 111, 0) 96%)',
    'taking': 'linear-gradient(90deg, #B276FF 0%, #74A7FF 41%, rgba(116, 167, 255, 0) 96%)',
    'completed': 'linear-gradient(90deg, #4CAF50 0%, #81C784 50%, rgba(76, 175, 80, 0) 96%)',
    'cancelled': 'linear-gradient(90deg, #9E9E9E 0%, #BDBDBD 50%, rgba(158, 158, 158, 0) 96%)'
  };
  return {
    background: styleMap[status] || 'linear-gradient(90deg, #B276FF 0%, #74A7FF 41%, rgba(116, 167, 255, 0) 96%)'
  };
};

// 计算已确认人数（status === 4 表示待发布人确认，即已确认）
const confirmedCount = computed(() => {
  return accepterList.value.filter(user => user.status === 4).length;
});

const loadOrderDetail = async () => {
  if (!orderId.value) {
    uni.showToast({
      title: '缺少订单ID',
      icon: 'none'
    });
    return;
  }

  loading.value = true;
  try {
    const res = await BuddyApi.getBuddyOrderDetail(orderId.value);
    if (res && res.code === 0 && res.data) {
      const data = res.data;
      const acceptUsers = Array.isArray(data.acceptUsers) ? data.acceptUsers : [];

      orderDetail.value = {
        id: data.id,
        title: data.title || '',
        buddyTypeName: data.buddyTypeName || '搭子',
        status: normalizePublishedStatus(data.status),
        publishTime: formatDateTime(data.publishTime || data.createTime || data.updateTime),
        eventTime: formatEventTime(data.startTime || data.appointmentTime),
        location: data.location || '',
        genderRestriction: formatGenderLimit(data.genderLimit),
        participantCount: data.participantCount || data.maxParticipants || 10,
        distance: formatDistance(data.distance),
        price: data.unitPrice || data.price || 0
      };

      // 处理接单人列表
      accepterList.value = acceptUsers.map(user => ({
        id: user.id || user.userId,
        nickname: user.nickname || user.name || '匿名用户',
        name: user.nickname || user.name || '匿名用户',
        avatar: user.avatar || '/static/avatars/default_avatar.png',
        status: user.status || 0 // 0-待确认，1-已确认，2-已拒绝
      }));
    } else {
      uni.showToast({
        title: res?.msg || '获取订单详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    uni.showToast({
      title: '获取订单详情失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

const handleConfirm = async (user) => {
  if (actionLoading.value) return;

  uni.showModal({
    title: '确认接单',
    content: `确定要确认"${user.nickname || user.name}"的接单申请吗？`,
    success: async (res) => {
      if (res.confirm) {
        actionLoading.value = true;
        try {
          const confirmRes = await BuddyApi.confirmAccepter(orderId.value, user.id);
          if (confirmRes && confirmRes.code === 0) {
            uni.showToast({
              title: '已确认',
              icon: 'success'
            });
            // 刷新订单详情
            await loadOrderDetail();
          } else {
            uni.showToast({
              title: confirmRes?.msg || '确认失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('确认接单失败:', error);
          uni.showToast({
            title: '确认失败，请稍后重试',
            icon: 'none'
          });
        } finally {
          actionLoading.value = false;
        }
      }
    }
  });
};

const handleReject = async (user) => {
  if (actionLoading.value) return;

  uni.showModal({
    title: '拒绝接单',
    content: `确定要拒绝"${user.nickname || user.name}"的接单申请吗？`,
    success: async (res) => {
      if (res.confirm) {
        actionLoading.value = true;
        try {
          const rejectRes = await BuddyApi.rejectAccepter(orderId.value, user.id);
          if (rejectRes && rejectRes.code === 0) {
            uni.showToast({
              title: '已拒绝',
              icon: 'success'
            });
            // 刷新订单详情
            await loadOrderDetail();
          } else {
            uni.showToast({
              title: rejectRes?.msg || '拒绝失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('拒绝接单失败:', error);
          uni.showToast({
            title: '拒绝失败，请稍后重试',
            icon: 'none'
          });
        } finally {
          actionLoading.value = false;
        }
      }
    }
  });
};


onLoad((options) => {
  if (options.id) {
    orderId.value = options.id;
    loadOrderDetail();
  } else {
    uni.showToast({
      title: '缺少订单ID',
      icon: 'none'
    });
    setTimeout(() => {
      goBack();
    }, 1500);
  }
});
</script>

<style lang="scss" scoped>
.confirm-order-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f6f7fb;
  position: relative;
}

.content-scroll {
  position: relative;
  height: 100vh;
  box-sizing: border-box;
  padding-bottom: 40rpx;
}

.order-detail-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 20rpx 17rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;

  &::after {
    content: '';
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    width: 160rpx;
    height: 160rpx;
    background-image: url('/static/game.png');
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    opacity: 0.12;
    pointer-events: none;
    z-index: 0;
  }

  > * {
    position: relative;
    z-index: 1;
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16rpx;

  .title-wrapper {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;

    .order-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 8rpx;
    }

    .buddy-type-badge {
      font-size: 24rpx;
      color: #F18F10;
      background-color: rgba(252, 231, 152, 0.42);
      padding: 4rpx 12rpx;
      border-radius: 8rpx;
      white-space: nowrap;
      flex-shrink: 0;
    }
  }

  .order-tags {
    display: flex;
    gap: 12rpx;
    flex-shrink: 0;
  }
}

.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #fff;
}

.publish-time {
  font-size: 24rpx;
  color: #000;
  margin-bottom: 16rpx;
  display: block;
}

.event-time,
.event-location {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 12rpx;

  .event-icon {
    width: 28rpx;
    height: 28rpx;
    margin-right: 8rpx;
  }
}

.detail-tags {
  display: flex;
  gap: 12rpx;
  margin-bottom: 20rpx;

  .detail-tag {
    padding: 6rpx 12rpx;
    background-color: #f0f0f0;
    border-radius: 16rpx;
    font-size: 22rpx;
    color: #666;
  }
}

.price-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;

  .price {
    font-size: 32rpx;
    font-weight: bold;
    color: #f44336;
  }
}

.card-bg {
  position: absolute;
  top: 0;
  right: 0;
  width: 180rpx;
  height: 180rpx;
  opacity: 0.15;
  pointer-events: none;

  .bg-image {
    width: 100%;
    height: 100%;
  }
}

.accepter-list-card {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 20rpx 17rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;

  .list-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .list-count {
    font-size: 28rpx;
    color: #666;
  }
}

.accepter-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.accepter-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .accepter-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 20rpx;
    flex-shrink: 0;
  }

  .accepter-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 0;
  }

  .accepter-name {
    font-size: 28rpx;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 8rpx;
  }

  .status-text {
    font-size: 24rpx;
    
    &.pending {
      color: #FF9800;
    }
    
    &.confirmed {
      color: #4CAF50;
    }
  }

  .accepter-actions {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 16rpx;
    flex-shrink: 0;
  }

  .status-badge {
    padding: 8rpx 20rpx;
    border-radius: 20rpx;
    font-size: 24rpx;
    color: #fff;

    &.confirmed {
      background-color: #4CAF50;
    }

    &.rejected {
      background-color: #f44336;
    }
  }

  .action-buttons {
    display: flex;
    gap: 16rpx;
  }

  .action-btn {
    padding: 10rpx 24rpx;
    border-radius: 24rpx;
    font-size: 26rpx;
    border: none;
    line-height: 1.2;
    min-width: 100rpx;

    &::after {
      border: none;
    }

    &.reject-btn {
      background-color: #eeeeee;
      color: #333;
    }

    &.confirm-btn {
      background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
      color: #fff;
    }

    &:disabled {
      opacity: 0.6;
    }
  }
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style>

